package com.sms.gateway.config;

import jakarta.annotation.Resource;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Mono;

@Configuration
public class GatewayConfig {


    // 定义限流键解析器（这里以请求路径作为限流键，可根据需求修改为IP、用户ID等）
    @Bean
    public KeyResolver pathKeyResolver() {
        return exchange -> Mono.just(
                exchange.getRequest().getPath().value() // 按路径限流
                //exchange.getAttribute("orderId") // 按订单ID限流
                // 按IP限流：exchange.getRequest().getRemoteAddress().getAddress().getHostAddress()
        );
    }

    // 配置Redis令牌桶限流规则（每秒生成2个令牌，桶容量为4）
    @Bean
    public RedisRateLimiter redisRateLimiter() {
        return new RedisRateLimiter(2, 4); // 第一个参数：每秒令牌数；第二个参数：桶容量
    }
} 